package com.shigen.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shigen.shop.entity.Address;
import com.shigen.shop.enums.BizCodeEnum;
import com.shigen.shop.exception.BizException;
import com.shigen.shop.inteceptor.LoginInterceptor;
import com.shigen.shop.mapper.AddressMapper;
import com.shigen.shop.req.AddressReq.AddAddressReq;
import com.shigen.shop.service.AddressService;
import com.shigen.shop.vo.AddressVO;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author shigenfu
 * @description 针对表【address(电商-公司收发货地址表)】的数据库操作Service实现
 * @createDate 2022-07-24 14:29:47
 */
@Service
@Slf4j
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {

  @Resource
  AddressMapper addressMapper;

  @Override
  public List<AddressVO> getAddressByUserId(Long userId) {
    List<Address> addressList = lambdaQuery().eq(userId != null, Address::getUserId, userId).list();
    ArrayList<AddressVO> addressVOS = new ArrayList<>();
    addressList.forEach(address -> {
      AddressVO addressVO = new AddressVO();
      BeanUtil.copyProperties(address, addressVO, true);
      addressVOS.add(addressVO);
    });
    return addressVOS;
  }

  @Override
  public int addAddress(AddAddressReq addressReq) {
    Address address = new Address();
    BeanUtil.copyProperties(addressReq, address, true);
    return getBaseMapper().insert(address);
  }

  @Override
  public int deleteAddressByUserId(Long userId) {
    if (userId == null) {
      throw new BizException(BizCodeEnum.PARAM_REQUIRED);
    }
    log.info("threadLocal: {}", LoginInterceptor.threadLocal.get());
    LambdaQueryWrapper<Address> wrapper = (LambdaQueryWrapper<Address>) lambdaQuery().eq(userId.equals(LoginInterceptor.threadLocal.get().getId()), Address::getUserId, 10).getWrapper();
    return addressMapper.delete(wrapper);
  }
}




